package net.gz01.wallet.channel.fadada;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import net.gz01.wallet.web.config.SystemConfig;
import net.gz01.wallet.web.controller.api.sdk.client.FddClientBase;
import net.gz01.wallet.web.controller.api.sdk.client.authForfadada.FindCertInfo;
import net.gz01.wallet.web.controller.api.sdk.client.authForfadada.GetCompanyVerifyUrl;
import net.gz01.wallet.web.controller.api.sdk.client.authForfadada.GetPersonVerifyUrl;
import net.gz01.wallet.web.controller.api.sdk.client.authForfadada.model.AgentInfoINO;
import net.gz01.wallet.web.controller.api.sdk.client.authForfadada.model.BankInfoINO;
import net.gz01.wallet.web.controller.api.sdk.client.authForfadada.model.CompanyInfoINO;
import net.gz01.wallet.web.controller.api.sdk.client.authForfadada.model.LegalInfoINO;
import net.gz01.wallet.web.controller.api.sdk.client.request.ExtsignReq;
import com.jfinal.kit.PathKit;
import net.gz01.util.ZOLog;
import net.gz01.wallet.channel.IChannel;
import net.gz01.wallet.message.*;
import net.gz01.wallet.web.config.FDDConfig;
import net.gz01.wallet.web.model.Merch;
import net.gz01.wallet.web.model.TradeOrder;
import net.gz01.wallet.web.model.base.FddOrder;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import static net.gz01.wallet.web.config.FDDConfig.*;
import static net.gz01.wallet.web.config.FDDConfig.HOST;
import static net.gz01.wallet.web.config.FDDConfig.V;

public class FadadaChannel implements IChannel {
    private final boolean isAutoSign = SystemConfig.config.getBoolean("isAutoSign");
    @Override
    public DFResp payment(DFReq req, TradeOrder order) {
        return null;
    }

    @Override
    public QueryResp query(QueryReq req, TradeOrder order) {
        return null;
    }

    public RealCompanyResp realNameCompany(RealCompanyReq req){

        RealCompanyResp resp = new RealCompanyResp();
        FddOrder order = FddOrder.dao.selectByUserCode(req.getOpen_id());
        if(order!=null && order.getCustomerId()!=null){
            resp.setRespCode(order.getResCode());
            resp.setUrl(new String(Base64.decodeBase64(order.getUrl())));
            resp.setTransactionNo(order.getFddOrderNo());
            resp.setCustomer_id(order.getCustomerId());
            return resp;
        }

        FddClientBase base = new FddClientBase(FDDConfig.fddappid,FDDConfig.fddapp_secret,fdd_V,fddhost_url);
        String open_id = req.getOpen_id(); //merch.getCode(); //商户号每一个客户唯一
        String account_type = req.getAccount_type();

        String res =base.invokeregisterAccount(open_id,account_type);
        ZOLog.api.info("FDD -->注册接口返回:" + res);

        String customer_id = null;
        if(res !=null){
            JSONObject json= JSON.parseObject(res);
            String code = json.getString("code");
            if("1".equals(code)){
                customer_id = json.getString("data");
            }else {
                resp.setRespCode("01");
                resp.setRespMsg(res);
                return resp;
            }
        }
        if(customer_id !=null){
            resp.setCustomer_id(customer_id);
            switch (account_type){
                case "1":
                    resp = personalRealName(resp, customer_id, req);
                    break;
                case "2":
                    resp = companyRealName(resp, customer_id, req);
                    break;
            }
            if("00".equals(resp.getRespCode())) {
                FddOrder fddOrder = new FddOrder();
                fddOrder.createOrder(req, resp);
            }
            return resp;
        }

        return null;

    }

    public QueryResp queryFadada(QueryReq req, FddOrder order, Merch user) {
        QueryResp resp = new QueryResp(req);
        if(!"3".equals(order.getType())) {
            FindCertInfo personCertInfo = new FindCertInfo(APP_ID, APP_SECRET, V, HOST);
            String verified_serialno = order.getFddOrderNo();
            String result = personCertInfo.invokeFindPersonCert(verified_serialno,
                    order.getType());
            if(StringUtils.isNotEmpty(result)) {
                ZOLog.api.info("实名查询接口返回:" + result);
                JSONObject jsonObject = JSON.parseObject(result);
                if(!"1".equals(jsonObject.getString("code"))){
                    resp.setCodeAndMsg("01", result);
                    return resp;
                }
                JSONObject object = jsonObject.getJSONObject("data");
                String type = object.getString("type");
                order.setJsondata(result);
                order.update();
                switch (type) {
                    case "1": {
                        JSONObject person = object.getJSONObject("person");
                        ZOLog.api.info("查询接口--个人:" + person.toJSONString());
                        String personName = person.getString("personName");
                        if (StringUtils.isNotEmpty(personName)) {
                            user.setLegalPerson(personName);
                            user.update();
                        }
                    }
                    break;
                    case "2": {
                        JSONObject company = object.getJSONObject("company");
                        JSONObject manager = object.getJSONObject("manager");
                        JSONObject bankCard = object.getJSONObject("bankCard");
                        String companyName = company.getString("companyName");
                        String personName = manager.getString("personName");

                        if (StringUtils.isNotEmpty(companyName)) {
                            user.setLegalPerson(companyName);
                            user.setContacts(personName);
                            user.update();
                        }

                        ZOLog.api.info("查询接口--企业:" + company.toJSONString());
                        ZOLog.api.info("查询接口--企业:" + manager.toJSONString());
                        ZOLog.api.info("查询接口--企业:" + bankCard.toJSONString());
                    }
                    break;
                }
            }
        }else {
            resp.setCodeAndMsg("01", "不支持的类型");
        }
        return resp;
    }


    public NetSignResp netsignNetHands(NetSignReq signReq){
        NetSignResp resp = new NetSignResp();
        String contract_id = signReq.getContract_id();
        FddClientBase base = new FddClientBase(APP_ID,APP_SECRET,V,HOST);

        String filepath = PathKit.getWebRootPath()+File.separator + signReq.getHeTongUrl();
        ZOLog.api.info("文件路径:" + filepath);
        File file = new File(filepath);
        //renderHtml("正在操作网签合同,请稍等...");
        String result = base.invokeUploadDocs(contract_id, signReq.getDoc_title(),
                file, null, ".pdf");

        ZOLog.api.info("FDD----合同上传接口返回:" + result);//{"code":"1000","msg":"操作成功","result":"success"}
        if(result!=null){
            String code = JSON.parseObject(result).getString("code");
            if (!"1000".equals(code)){
                resp.setCodeAndMsg("01", result);
                return resp;
            }

            //调用签署接口
            FddClientBase baseV = new FddClientBase(APP_ID,APP_SECRET,V,HOST);
            ExtsignReq req = new ExtsignReq();
            req.setCustomer_id(signReq.getCustomer_id());
            req.setTransaction_id(signReq.getTransaction_id());//签署交易号随机生成);

            req.setContract_id(contract_id);
            req.setDoc_title(signReq.getDoc_title());
            req.setPosition_type("0");
            req.setSign_keyword(signReq.getSign_keyword());
            req.setKeyword_strategy("0");//关键字签章策略：//0：所有关键字签章 （默认）；1：第一个关键字签章 ； 2：最后一个关键字签章；
            req.setReturn_url(fdd_return_url_sign);
            req.setNotify_url(fdd_notify_url_sign);
            String resultV = baseV.invokeExtSign(req);

            ZOLog.api.info("FDD----合同手工签署接口返回:" + resultV);
            if(resultV==null){
                resp.setCodeAndMsg("01", "ERROR -1: result == null");
                return resp;
            }else {
                FddOrder order = new FddOrder();
                order.createOrderSign(signReq, resultV);
                resp.setCodeAndMsg("00", "成功");
                resp.setUrl(resultV);
            }
            //redirect(resultV);
        }else {
            resp.setCodeAndMsg("01", "合同上传ERROR: result == null");
        }

        return resp;
    }


    //自动签署合同的 接口调用
    public NetSignResp netsignNet(NetSignReq signReq){

        if(!isAutoSign){
            return netsignNetHands(signReq);
        }


        NetSignResp resp = new NetSignResp();
        String contract_id = signReq.getContract_id();
        FddClientBase base = new FddClientBase(APP_ID,APP_SECRET,V,HOST);

        String filepath = PathKit.getWebRootPath()+File.separator + signReq.getHeTongUrl();
        ZOLog.api.info("文件路径:" + filepath);
        File file = new File(filepath);
        //renderHtml("正在操作网签合同,请稍等...");
        String result = base.invokeUploadDocs(contract_id, signReq.getDoc_title(),
                file, null, ".pdf");

        ZOLog.api.info("FDD----合同上传接口返回:" + result);//{"code":"1000","msg":"操作成功","result":"success"}
        if(result!=null){
            String code = JSON.parseObject(result).getString("code");
            if (!"1000".equals(code)){
                resp.setCodeAndMsg("01", result);
                return resp;
            }

            //调用签署接口
            FddClientBase baseV = new FddClientBase(APP_ID,APP_SECRET,V,HOST);
            ExtsignReq req = new ExtsignReq();
            req.setCustomer_id(signReq.getCustomer_id());
            req.setTransaction_id(signReq.getTransaction_id());//签署交易号随机生成);

            req.setContract_id(contract_id);
            req.setDoc_title(signReq.getDoc_title());
            req.setReturn_url(fdd_return_url_sign);
            req.setNotify_url(fdd_notify_url_sign);
            req.setPosition_type("0");
            req.setSign_keyword(signReq.getSign_keyword());
            req.setKeyword_strategy("0");//关键字签章策略：//0：所有关键字签章 （默认）；1：第一个关键字签章 ； 2：最后一个关键字签章；
            req.setClient_role("3");
            String resultV = baseV.invokeExtSignAuto(req);

            ZOLog.api.info("FDD----合同自动签署接口返回:" + resultV);
            if(resultV==null){
                resp.setCodeAndMsg("01", "ERROR -1: result == null");
                return resp;
            }else {
                JSONObject json = JSON.parseObject(resultV);
                if("1000".equals(json.getString("code"))) {
                    FddOrder order = new FddOrder();
                    order.createOrderSignAuto(signReq, json);
                    String download_url = json.getString("download_url");
                    String viewpdf_url = json.getString("viewpdf_url");

                    Merch merch = Merch.dao.selectByMerchCode(order.getUserCode());
                    merch.setIsSign(true);
                    merch.setDownloadUrl(download_url);
                    merch.setViewpdfUrl(viewpdf_url);
                    merch.setContractId(order.getContractId());
                    merch.setTransactionId(order.getFddOrderNo());
                    merch.update();
                    resp.setCodeAndMsg("00", "成功");
                    resp.setUrl("/customer/index");
                }else {
                    resp.setCodeAndMsg("01", resultV);
                }
            }
        }else {
            resp.setCodeAndMsg("01", "合同上传ERROR: result == null");
        }

        return resp;
    }


    private RealCompanyResp companyRealName(RealCompanyResp resp, String customer_id, RealCompanyReq req){
        GetCompanyVerifyUrl comverify = new GetCompanyVerifyUrl(APP_ID,APP_SECRET,V,HOST);
        CompanyInfoINO companyInfo = new CompanyInfoINO();
        companyInfo.setCompany_name("");
        companyInfo.setCredit_no("");
        companyInfo.setCredit_image_path("");

        BankInfoINO bankInfo = new BankInfoINO();
        bankInfo.setBank_name("");
        bankInfo.setBank_id("");
        bankInfo.setSubbranch_name("");

        LegalInfoINO legalInfo = new LegalInfoINO();
        legalInfo.setLegal_name("");
        legalInfo.setLegal_id("");
        legalInfo.setLegal_mobile("");
        legalInfo.setLegal_id_front_path("");

        AgentInfoINO agentInfo = new AgentInfoINO();
        agentInfo.setAgent_name("");
        agentInfo.setAgent_id("");
        agentInfo.setAgent_mobile("");
        agentInfo.setAgent_id_front_path("");
        //String customer_id = "";//必填
        /**
         * 实名认证套餐类型
         * 0：标准方案（对公打款+纸质审核）默认0；
         * 1：对公打款；
         * 2：纸质审核',
         */
        String verifyed_way = "2";
        String page_modify = "1";//必填
        String company_principal_type = "1";//1.法人，2代理人
        String notify_url = FDDConfig.fdd_notify_url_verify; //req.getNotify_url();//必填
        String return_url = req.getReturn_url();//可填
        String result = comverify.invokeCompanyVerifyUrl(companyInfo,bankInfo,legalInfo
                ,agentInfo, customer_id,verifyed_way,page_modify,
                company_principal_type,return_url,notify_url);
        ZOLog.api.info("FDD -->获取企业实名接口返回:" + result);
        String data = JSON.parseObject(result).getString("data");
        if (null !=data){
            String url = JSON.parseObject(data).getString("url");
            String transactionNo = JSON.parseObject(data).getString("transactionNo");
            if(transactionNo!=null && transactionNo.length()>0) {
                resp.setRespCode("00");
                resp.setTransactionNo(transactionNo);
                url = decode(url);
                System.out.println("FDD---URL--> :" + url);
                resp.setUrl(url);
                return resp;
            }
        }
        return null;
    }

    private RealCompanyResp personalRealName( RealCompanyResp resp, String customer_id, RealCompanyReq req){
        GetPersonVerifyUrl personverify = new GetPersonVerifyUrl(APP_ID,APP_SECRET,V,HOST);
        String verifyed_way = "1";
        String page_modify = "1";
        String notify_url = FDDConfig.fdd_notify_url_verify; //req.getNotify_url();
        String return_url= fdd_return_url_verify;
        String customer_name = req.getCustomer_name();
        String customer_ident_type = "0";
        String customer_ident_no =req.getCustomer_ident_no();
        String mobile =req.getMobile();
        String ident_front_path =req.getIdent_front_path();
        String result = personverify.invokePersonVerifyUrl(customer_id,verifyed_way,
                page_modify,notify_url,return_url,customer_name,customer_ident_type,
                customer_ident_no,mobile,ident_front_path);

        ZOLog.api.info("FDD -->获取个人实名接口返回:" + result);
        String code = JSON.parseObject(result).getString("code");
        if (!"1".equals(code)){
            resp.setRespCode("01");
            resp.setRespMsg(result);
            return resp;
        }
        String data = JSON.parseObject(result).getString("data");
        if (null !=data){
            String url = JSON.parseObject(data).getString("url");
            String transactionNo = JSON.parseObject(data).getString("transactionNo");
            if(transactionNo!=null && transactionNo.length()>0) {
                resp.setRespCode("00");
                resp.setTransactionNo(transactionNo);
                url = decode(url);
                System.out.println("FDD---URL--> :" + url);
                resp.setUrl(url);
                return resp;
            }
        }
        return null;
    }

    private String decode(String bizContent) {
        try {
            bizContent = URLDecoder.decode(bizContent, "utf-8");
            bizContent = new String(Base64.decodeBase64(bizContent.getBytes()));
        } catch (UnsupportedEncodingException e) {
            return "";
        }
        return bizContent;
    }
}
